package clipboard

import (
	"clipPaste/internal/storage"
	"crypto/sha256"
	"encoding/hex"
	"log"
	"time"

	"fyne.io/fyne/v2"
)

type Manager struct {
	store    *storage.Manager
	app      fyne.App
	mainWin  fyne.Window
	lastHash string
}

func NewManager(app fyne.App, store *storage.Manager) *Manager {
	// 创建主窗口
	mainWin := app.NewWindow("ClipPaste")
	mainWin.Resize(fyne.NewSize(1, 1))
	mainWin.Hide()

	return &Manager{
		store:   store,
		app:     app,
		mainWin: mainWin,
	}
}

func (m *Manager) StartMonitoring() {
	if m.mainWin == nil {
		log.Fatal("Main window not initialized")
	}

	time.Sleep(time.Second)

	go func() {
		ticker := time.NewTicker(500 * time.Millisecond)
		defer ticker.Stop()

		for range ticker.C {
			if clip := m.mainWin.Clipboard(); clip != nil {
				// 检查文本内容
				if content := clip.Content(); content != "" {
					m.handleTextContent(content)
				}
			}
		}
	}()

	go func() {
		m.mainWin.Show()
		m.mainWin.Hide()
	}()
}

func (m *Manager) handleTextContent(content string) {
	currentHash := m.hashContent(content)
	if currentHash == m.lastHash {
		return
	}

	m.lastHash = currentHash

	clip := &storage.ClipItem{
		Type:      storage.TypeText,
		Content:   content,
		Timestamp: time.Now(),
		Preview:   content,
		Size:      int64(len(content)),
		Hash:      currentHash,
	}

	if err := m.store.SaveClip(clip); err != nil {
		log.Printf("Failed to save text clip: %v", err)
	} else {
		log.Printf("Saved new text clip: %s", truncateString(clip.Preview, 50))
	}
}

func (m *Manager) hashContent(content string) string {
	hasher := sha256.New()
	hasher.Write([]byte(content))
	return hex.EncodeToString(hasher.Sum(nil))
}

func truncateString(s string, maxLen int) string {
	if len(s) <= maxLen {
		return s
	}
	return s[:maxLen-3] + "..."
}
